package com.cuotigou.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.common.SMSClient;
import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;




import java.util.*;

import static com.cuotigou.config.PayConfig.APP_KEY;

public class HttpClientUtil {

    public ObjectResult sendPost(String url, String xml){
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;

        client = HttpClients.createDefault();
        URI uri = null;
        try {
            uri = new URI(url);
        } catch (URIException e) {
            e.printStackTrace();
        }
        HttpPost post = new HttpPost(String.valueOf(uri));
        List<BasicNameValuePair> formList = new ArrayList<>();

        formList.add(new BasicNameValuePair("FM", xml));
        StringEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(formList, "utf-8");

            post.setEntity(entity);

            //设置请求的报文头部的编码
            post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));

            //设置期望服务端返回的编码
            post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));

            //执行post请求
            response = client.execute(post);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200){
                return ObjectResult.build("0","服务器异常0x02,请稍后重试");
            }

            String resStr = EntityUtils.toString(response.getEntity());

            return ObjectResult.build("1", resStr);
        } catch (Exception e) {
            e.printStackTrace();
            return ObjectResult.build("0", "服务器异常0x02,请稍后重试");
        }finally {
            try {
                response.close();
                client.close();
            }catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    public static ObjectResult verificationOfBankCard(String url, Map<String, String> map){
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;

        client = HttpClients.createDefault();
        URI uri = null;
        try {
            uri = new URI(url);
        } catch (URIException e) {
            e.printStackTrace();
        }
        HttpPost post = new HttpPost(String.valueOf(uri));
        List<BasicNameValuePair> formList = new ArrayList<>();

        Set set2 = map.entrySet();
        for(Iterator iter = set2.iterator(); iter.hasNext();){
            Map.Entry entry = (Map.Entry)iter.next();
            formList.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
        }

        StringEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(formList, "utf-8");

            post.setEntity(entity);

            //设置请求的报文头部的编码
            post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));

//			//设置期望服务端返回的编码
//			post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));


            String str =  JSMSExample.appkey+":"+JSMSExample.masterSecret;

            post.setHeader(new BasicHeader("Authorization", "Basic "+CommonUtils.encryptByBase64(str)));

            //执行post请求
            response = client.execute(post);

//			int statusCode = response.getStatusLine().getStatusCode();
//			if (statusCode != 200){
//				return ObjectResult.build("0","服务器异常0x02,请稍后重试");
//			}

            String resStr = EntityUtils.toString(response.getEntity());
            System.out.println("======接收的json======"+resStr);

            Map<String,String> stringStringMap = (Map<String,String>) JSON.parse(resStr);
            System.out.println("======转换的map======"+stringStringMap);

            return ObjectResult.build("1", "", stringStringMap);
        } catch (Exception e) {

            return ObjectResult.build("0", "服务器异常0x02,请稍后重试");
        }finally {
            try {
                response.close();
                client.close();
            }catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


//    public static JSONObject post(String url, JSONObject jsonData) {
//        JSONObject result = new JSONObject();
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        CloseableHttpResponse response = null;
//        try {
//            HttpPost httpPost = new HttpPost(url);
//            httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
//
//            httpPost.addHeader("Authorization", "Basic "+CommonUtils
//                    .encryptByBase64(JSMSExample.appkey+":"+JSMSExample.masterSecret));
//
//            if (jsonData != null && !jsonData.isEmpty()){
//                List<BasicNameValuePair> nameValuePairs = new ArrayList<>();
//                Set<Entry<String, Object>> set = jsonData.entrySet();
//                for (Entry<String, Object> entry : set){
//                    String key = entry.getKey();
//                    String value = entry.getValue().toString();
//                    nameValuePairs.add(new BasicNameValuePair(key, value));
//                }
//                httpPost.setEntity(new UrlEncodedFormEntity((List<? extends org.apache.http.NameValuePair>) nameValuePairs, "UTF-8"));
//            }
//
//            response = httpClient.execute(httpPost);
//            HttpEntity entity = response.getEntity();
//            int statusCode = response.getStatusLine().getStatusCode();
//            result.put("status_code", statusCode);
//            if (entity != null) {
//                result.put("data", EntityUtils.toString(entity));
//            }
//        } catch (ClientProtocolException e) {
//            System.out.println("连接" + url + "失败，原因为" + e.getMessage());
//        } catch (ParseException e) {
//            System.out.println("连接" + url + "失败，原因为" + e.getMessage());
//        } catch (IOException e) {
//            System.out.println("连接" + url + "失败，原因为" + e.getMessage());
//        } finally {
//            if (response != null){
//                try {
//                    response.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            if (httpClient != null){
//                try {
//                    httpClient.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return result;
//    }


    public static void main(String[] args) {
//        SMSClient  client = new SMSClient(JSMSExample.masterSecret, JSMSExample.appkey);
//
//		SMSPayload payload = SMSPayload.newBuilder()
//				.setMobileNumber("13758876025")
//				.setTempId(1)
//				.build();
//
//		JsonObject json = new JsonObject();
//		json.addProperty("mobile", "13758876025");
//		json.addProperty("temp_id", 1);
//
////		assertEquals(payload.toJSON(), json);
//
//		try {
//			SendSMSResult res = client.sendSMSCode(payload);
////			assertTrue(res.isResultOK());
//			System.out.println("res:"+ res.toString());
//		} catch (APIConnectionException e) {
//			e.printStackTrace();
//		} catch (APIRequestException e) {
//			e.printStackTrace();
//		}
//
    }
}
